<script setup>
import { ref, onMounted } from 'vue';
import { getMyArticles, deleteArticle, updateArticle, getCommunityCategories } from '@/api/community';
import { uploadFile } from '@/api/common';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const articleList = ref([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const editDialogVisible = ref(false);
const editForm = ref({});
const editLoading = ref(false);
const categories = ref([]);
const categoriesLoading = ref(false);

const loadMyArticles = async () => {
  loading.value = true;
  try {
    const res = await getMyArticles({ page: page.value, pageSize: pageSize.value });
    if ((res.code === 0 || res.code === 200) && res.data) {
      articleList.value = res.data.records || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.message || '获取文章失败');
    }
  } finally {
    loading.value = false;
  }
};

// 加载分类列表
const loadCategories = async () => {
  categoriesLoading.value = true;
  try {
    const res = await getCommunityCategories();
    if ((res.code === 0 || res.code === 200) && res.data) {
      categories.value = res.data || [];
    } else {
      ElMessage.error(res.message || '获取分类列表失败');
    }
  } finally {
    categoriesLoading.value = false;
  }
};

// 上传图片
const handleUploadCover = async (file) => {
  try {
    const res = await uploadFile(file);
    if ((res.code === 0 || res.code === 200) && res.data) {
      editForm.value.coverImage = res.data.url || res.data; // 兼容不同后端返回
      ElMessage.success('封面图片上传成功');
    } else {
      ElMessage.error(res.message || '图片上传失败');
    }
  } catch (e) {
    console.error('图片上传失败:', e);
    ElMessage.error('图片上传失败');
  }
};

const handlePageChange = (val) => {
  page.value = val;
  loadMyArticles();
};
const handleSizeChange = (val) => {
  pageSize.value = val;
  page.value = 1;
  loadMyArticles();
};

const viewArticleDetail = (id) => {
  router.push(`/community/article/${id}`);
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该文章吗？', '提示', { type: 'warning' });
    const res = await deleteArticle(row.id);
    if ((res.code === 0 || res.code === 200) && res.data) {
      ElMessage.success('删除成功');
      loadMyArticles();
    } else {
      ElMessage.error(res.message || '删除失败');
    }
  } catch (e) {
    // 用户取消
  }
};

const handleEdit = async (row) => {
  // 先加载分类列表
  if (categories.value.length === 0) {
    await loadCategories();
  }
  
  editForm.value = { ...row };
  // 确保categoryId是数字类型
  if (editForm.value.categoryId && typeof editForm.value.categoryId === 'string') {
    editForm.value.categoryId = Number(editForm.value.categoryId);
  }
  editDialogVisible.value = true;
};

const handleEditSubmit = async () => {
  // 表单验证
  if (!editForm.value.title?.trim()) {
    ElMessage.warning('请输入文章标题');
    return;
  }
  if (!editForm.value.content?.trim()) {
    ElMessage.warning('请输入文章内容');
    return;
  }
  if (!editForm.value.categoryId) {
    ElMessage.warning('请选择文章分类');
    return;
  }

  editLoading.value = true;
  try {
    const payload = {
      id: editForm.value.id,
      title: editForm.value.title,
      content: editForm.value.content,
      summary: editForm.value.summary || '',
      coverImage: editForm.value.coverImage || '',
      images: editForm.value.images || '',
      categoryId: Number(editForm.value.categoryId),
      status: Number(editForm.value.status || 1)
    };
    const res = await updateArticle(payload.id, payload);
    if ((res.code === 0 || res.code === 200) && res.data) {
      ElMessage.success('更新成功');
      editDialogVisible.value = false;
      loadMyArticles();
    } else {
      ElMessage.error(res.message || '更新失败');
    }
  } finally {
    editLoading.value = false;
  }
};

onMounted(() => {
  loadMyArticles();
  loadCategories();
});
</script>

<template>
  <div class="my-articles-container">
    <h2>我的文章</h2>
    <el-table :data="articleList" v-loading="loading" style="width: 100%; margin-bottom: 20px;">
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="scope">
          <el-link @click="viewArticleDetail(scope.row.id)">{{ scope.row.title }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="categoryName" label="分类" min-width="100" />
      <el-table-column prop="createTime" label="创建时间" min-width="160" />
      <el-table-column prop="viewCount" label="浏览量" min-width="80" />
      <el-table-column prop="likeCount" label="点赞数" min-width="80" />
      <el-table-column prop="commentCount" label="评论数" min-width="80" />
      <el-table-column prop="status" label="状态" min-width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">已发布</el-tag>
          <el-tag v-else-if="scope.row.status === 0" type="info">草稿</el-tag>
          <el-tag v-else type="danger">已下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="160">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click.stop="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :current-page="page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      style="margin-top: 20px; display: flex; justify-content: flex-end;"
    />
    <el-dialog v-model="editDialogVisible" title="编辑文章" width="650px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="标题" required>
          <el-input v-model="editForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="内容" required>
          <el-input type="textarea" v-model="editForm.content" rows="8" placeholder="请输入文章内容" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input type="textarea" v-model="editForm.summary" rows="3" placeholder="请输入文章摘要，不填则自动提取内容前200字" />
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
            class="cover-uploader"
            action=""
            :http-request="({ file }) => handleUploadCover(file)"
            :show-file-list="false"
          >
            <div v-if="editForm.coverImage" class="image-preview">
              <img :src="editForm.coverImage" class="preview-image" />
            </div>
            <el-button v-else type="primary">上传封面图</el-button>
          </el-upload>
          <div v-if="editForm.coverImage" style="margin-top: 10px; display: flex; gap: 10px; align-items: center;">
            <el-button size="small" type="danger" @click="editForm.coverImage = ''">
              移除图片
            </el-button>
            <el-input v-model="editForm.coverImage" placeholder="或直接输入图片URL" style="flex: 1;" />
          </div>
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="editForm.categoryId" placeholder="请选择文章分类" style="width: 100%;">
            <el-option 
              v-for="cat in categories" 
              :key="cat.id" 
              :label="cat.name" 
              :value="cat.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status" style="width: 100%;">
            <el-option :value="1" label="已发布" />
            <el-option :value="0" label="草稿" />
            <el-option :value="2" label="已下架" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="handleEditSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.my-articles-container {
  max-width: 900px;
  margin: 40px auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  padding: 32px 24px;
}
h2 {
  margin-bottom: 24px;
  font-size: 24px;
  color: #222;
}
.cover-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
}
.image-preview {
  width: 200px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px dashed #d9d9d9;
  display: flex;
  justify-content: center;
  align-items: center;
}
.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}
</style> 